package qualomelhor.gwt.modules.client;

import java.util.ArrayList;
import qualomelhor.database.Avatar;
import qualomelhor.database.Comparacao;
import qualomelhor.database.ParametrosSistema;
import qualomelhor.database.ParametrosSistema.SiteHost;
import qualomelhor.database.Produto;
import qualomelhor.database.Usuario;
import qualomelhor.gwt.modules.client.event.ImagemDisponivelEvent;
import qualomelhor.gwt.modules.client.event.ImagemNaoDisponivelEvent;
import qualomelhor.gwt.modules.client.event.ImagensJaSelecionadasEvent;
import qualomelhor.gwt.modules.client.interfaces.BuscaImagemEventHandler;
import com.google.appengine.api.datastore.Blob;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.CanvasPixelArray;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class CriarComparacao2Coisas implements EntryPoint {
	private RootPanel rootSelProd1;
	private RootPanel rootProd1;
	private RootPanel rootSelProd2;
	private RootPanel rootProd2;
	private RootPanel rootPergunta;
	private ImageSliderWidget isw1;
	private ImageSliderWidget isw2;
	private BuscaImagemWidget biProd1;
	private BuscaImagemWidget biProd2;
	private ArrayList<String> listImageDataUrlProd1 = new ArrayList<String>(0);
	private ArrayList<String> listImageDataUrlProd2 = new ArrayList<String>(0);
	private VerticalPanel vertPanelPergunta;
	private FlexTable tbPanelPergunta;
	private VerticalPanel vertPanelProd1;
	private int guiaAtualProd1;
	private VerticalPanel vertPanelProd2;
	private VerticalPanel vertPanelAtualProd1;
	final VerticalPanel tmpVertPanelProd1_Show = new VerticalPanel();
	final VerticalPanel tmpVertPanelProd2_Show = new VerticalPanel();
	private VerticalPanel vertPanelAtualProd2;
	private TextBox txtBuscaProd1;
	private Button btnNextP1;
	private HandlerRegistration lbHldRegisProd1;
	private HandlerRegistration lbHldRegisProd1_blur;
	private Label lbProduto1;
	private TextBox txtBuscaProd2;
	private HandlerRegistration lbHldRegisProd2;
	private HandlerRegistration lbHldRegisProd2_blur;
	private Label lbProduto2;
	private ListBox listPerguntas;
	private Label lbPergPersonalizada;
	private TextBox txtPerguntaPersonalizada;
	private HandlerRegistration lbHldRegisPerg;
	private HandlerRegistration lbHldRegisPerg_blur;
	private Label lbPerguntaFinal;
	private HTMLPanel htmlP = new HTMLPanel("<video style=\"width: 100%; height: 250px; border: thin solid black;\" autoplay></video>");
	private HTMLPanel htmlPCanvas = new HTMLPanel("<canvas class=\"canvasVideo\" style=\"display:none;\"></canvas>");
	private final HTMLPanel htmlImg = new HTMLPanel("<img class=\"imgFoto\" style=\"width: 100%; height: 300px;\" />");
	private HTMLPanel htmlFile;
	private HTMLPanel htmlInputFile = new HTMLPanel("<input type=\"file\" id=\"files\" name=\"files\" />");
	private FileUpload upload;
	private ISessionSuportServiceAsync serviceSupportSvc = GWT.create(ISessionSuportService.class);
	private LanguageConstants constants = GWT.create(LanguageConstants.class);
	private LanguageMessages messages = GWT.create(LanguageMessages.class);
	private Usuario u;
	private String locale;
	private boolean comparacaoCarregada = false;

	int currentRow;
	FlexTable resultsTable;

	public static native void hideDivBloqueio()  /*-{
		$doc.getElementById("divBloqueio").style.display="none";
		$doc.getElementById("divBloqueioSolido").style.display="none";
	}-*/;

	public static native void showDivBloqueio()  /*-{
		$doc.getElementById("divBloqueio").style.display="block";
		$doc.getElementById("divBloqueioSolido").style.display="block";
	}-*/;

	private static native CanvasPixelArray getCPA(Element canvas, int sx, int sy, int sw, int sh) /*-{
	    return canvas.getContext("2d").getImageData(sx, sy, sw, sh);
	}-*/;

	//then, create one in your code:
	public static byte[] getBitmap(Element canvasElement, int left, int top, int width, int height) {
	    //then, create one in your code:
	    CanvasPixelArray cpa = getCPA(canvasElement, left, top, width, height);
	    byte[] pixelBytes = getBitmap(cpa);
	    return pixelBytes;
	}

	public static native Blob dataUrlToBlob(String dataUrl) /*-{
		$wnd.alert("$wnd.dataURLtoBlob = " + $wnd.dataURLtoBlob);
	    return $wnd.dataURLtoBlob(dataUrl);
	}-*/;

	public static byte[] getBitmap(CanvasPixelArray cpa) {
	    //then, create one in your code:
	    byte[] pixelBytes = new byte[cpa.getLength()];
	    for (int i = 0; i < cpa.getLength(); i++) {
	       pixelBytes[i] = (byte)cpa.get(i);
	    }
	    return pixelBytes;
	}

	public native String getImageData(int left, int top, int width, int height) /*-{

		//var oData = th...@com.messenger.client.framework.canvas::context.getImageData(left, top, width, height);

		var aImgData = oData.data;

		var strPixelData = "";
		var y = height;
		var iPadding = (4 - ((width * 3) % 4)) % 4;
		do {
			var iOffsetY = width*(y-1)*4;
			var strPixelRow = "";
			for (var x=0;x<width;x++) {
				var iOffsetX = 4*x;
				if (aImgData[iOffsetY+iOffsetX+2] == 0 && aImgData[iOffsetY+iOffsetX+1] == 0 &&	aImgData[iOffsetY+iOffsetX] == 0) {
					strPixelRow += String.fromCharCode(255);
					strPixelRow += String.fromCharCode(255);
					strPixelRow += String.fromCharCode(255);
				} else {
					strPixelRow +=
					String.fromCharCode(aImgData[iOffsetY+iOffsetX+2]);
					strPixelRow += String.fromCharCode(aImgData[iOffsetY+iOffsetX+1]);
					strPixelRow += String.fromCharCode(aImgData[iOffsetY+iOffsetX]);
				}
			}
			for (var c=0;c<iPadding;c++) {
				strPixelRow += String.fromCharCode(0);
			}
			strPixelData += strPixelRow;
		} while (--y);

		return strPixelData;
	}-*/;

	private static Blob canvasToBlob(Canvas c) {
		Blob result = new Blob(getBitmap(c.getElement(), 0, 0, c.getOffsetWidth(), c.getOffsetHeight()));
		return result;
	}

	private static ArrayList<Blob> listImageDataToListBlob (ArrayList<CanvasPixelArray> listCpa) {
		ArrayList<Blob> result = new ArrayList<Blob>(0);
		for (CanvasPixelArray cpa: listCpa) {
			result.add(new Blob(getBitmap(cpa)));
		}
		return result;
	}

	private static ArrayList<Blob> listDataUrlToListBlob (ArrayList<String> listDataUrl) {
		ArrayList<Blob> result = new ArrayList<Blob>(0);
		for (String dataUrl: listDataUrl) {
			result.add(dataUrlToBlob(dataUrl));
		}
		return result;
	}

	public static native void exportaVerificaComparacaoCarregada(CriarComparacao2Coisas compInstance) /*-{
		$wnd.verificaComparacaoCarregada_j = function () {
			return compInstance.@qualomelhor.gwt.modules.client.CriarComparacao2Coisas::verificaComparacaoCarregada()();
		}
	}-*/;

	private static native boolean gameCarregado () /*-{ 
		if ($wnd.verificaGameCarregado_j) {
			return $wnd.verificaGameCarregado_j();
		} else {
			return false;
		}
	}-*/;

	private static native String getStringAvatar () /*-{ 
		if ($wnd.getStringAvatar_j) {
			return $wnd.getStringAvatar_j();
		} else {
			return null;
		}
	}-*/;

	public static native void setMsgTextGWT(String txt, boolean hideOnTime) /*-{
		//alert($wnd.sendMsgText2_j);
		if ($wnd.sendMsgText2_j) {
			//alert("dentro do if...");
			$wnd.sendMsgText2_j(txt, hideOnTime);
			//alert("executou o sendmsgtext2...");
		} else {
			$wnd.alert("sendMsgText2_j nao pronto");
		}
	}-*/;

	public static native void carregaSequenciaExpressaoGWT(String nome) /*-{
		if ($wnd.carregaSequenciaExpressao_j) {
			//$wnd.alert("vai chamar o carregamento da sequencia expressao...");
			$wnd.carregaSequenciaExpressao_j(nome, false);
		}
	}-*/;

	public static native void moveMaoDClientGWT(int x, int y, float ang) /*-{
		$wnd.moveMaoD(x, y, ang);
	}-*/;

	public static native void startMoveMaoDClientGWT(int x, int y, float ang) /*-{
		$wnd.startMoveMaoD(x, y, ang);
	}-*/;

	public static native void trocaCaraClientGWT() /*-{
		//$wnd.alert("teste");
		//$wnd.alert($wnd.trocaCara);
		$wnd.trocaCara();
	}-*/;

	public static native void trocaAvatarGWT(boolean update) /*-{
		$wnd.trocaAvatarAleatorio_j(update);
	}-*/;

	public static native void trocaPosicaoMaosClientGWT(int posMaos) /*-{
		$wnd.trocaMaos(posMaos);
	}-*/;

	public static native void trocaExpressaoClientGWT(int expressao) /*-{
		//$wnd.alert("teste");
		//$wnd.alert($wnd.trocaExpressao);
		$wnd.trocaExpressao(expressao);
	}-*/;

	public static native void trocaSequenciaExpressao(int sequenciaExpressao) /*-{
		$wnd.trocaSequenciaExpressao(sequenciaExpressao);
	}-*/;

	public static native void startIniciaAleatorio(int tipo) /*-{
		$wnd.iniciaAleatorio(tipo);
	}-*/;

	public static native void iniciaComportamentoAleatorio(int tempo, int nivel) /*-{
		$wnd.iniciaComportamentoAleatorio_j(tempo, nivel);
	}-*/;

	public static native void trocaAvatarAleatorio(boolean update) /*-{
		$wnd.trocaAvatarAleatorio_j(update);
	}-*/;

	public static native void aplyToolTip() /*-{
		$wnd.aplicarToolTip();
	}-*/;

	public static native void removerToolTip() /*-{
		$wnd.removerToolTip();
	}-*/;

	public static native boolean verificaBackGroundCarregado() /*-{
		var result = false;
		if ($wnd.verificaBackgroundCarregado_j && $wnd.verificaBackgroundCarregado_j()) {
			result = true;
		}
		return result;
	}-*/;

	public static native String foto() /*-{
		return $wnd.snapshot();
	}-*/;

	public static native boolean hasGetUserMedia() /*-{
		if (!$wnd.hasGetUserMedia) {
			$wnd.hasGetUserMedia = function() {
				// Note: Opera is unprefixed.
				return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
	 			            navigator.mozGetUserMedia || navigator.msGetUserMedia);
	 		}
		}
		return $wnd.hasGetUserMedia();
	 	//$wnd.alert("hasGetUserMedia ok");
	}-*/;

	public static native boolean hasFileReader() /*-{
		var result = false;
		if ($wnd.File && $wnd.FileReader && $wnd.FileList && $wnd.Blob) {
	  		// Great success! All the File APIs are supported.
	  		result = true;
		} else {
		  	//$wnd.alert('The File APIs are not fully supported in this browser.');
		}

		return result;
	}-*/;	

	public static native void loadCam(String strTextoBoneco) /*-{

		//$wnd.alert("inicio loadcam");
		$wnd.localMediaStream = null;
		$wnd.ctx = null;
	 	$wnd.video = $doc.querySelector('video');
	 	$wnd.canvas = $doc.querySelector(".canvasVideo");
		//$wnd.alert("video = " + video);

	 	//video.addEventListener('click', snapshot, false);
		//$wnd.alert("video click ok");

		//$wnd.alert("$doc.getElementById = " + $doc.getElementById);
		//canvas = $doc.querySelector('canvas');
			
		//$wnd.alert("canvas = " + $wnd.canvas);
		//$wnd.alert("canvas.getContext = " + $wnd.canvas.getContext);
		$wnd.ctx = $wnd.canvas.getContext('2d');
		//$wnd.alert("ctx = " + $wnd.ctx);

		var onFailSoHard = function(e) {
			console.log('Reeeejected!', e);
		};

		//$wnd.alert("onFailSoHard ok");

		//$wnd.alert("snapshot ok");

	 	 if ($wnd.hasGetUserMedia()) {
	 		// Good to go!
	 		//$wnd.alert("getUserMedia ok");
	 	} else {
	 		$wnd.alert('getUserMedia() is not supported in your browser');
	 	}

		$wnd.URL = $wnd.URL || $wnd.webkitURL;
	 	//$wnd.alert("wnd.URL = " + $wnd.URL);
		navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
	 	//$wnd.alert("navigator.getUserMedia = " + navigator.getUserMedia);			

		if (navigator.getUserMedia) {
			//$wnd.alert("1");
			navigator.getUserMedia({video: true}, function(stream) {
				//$wnd.alert("2");
				$wnd.video.src = $wnd.URL.createObjectURL(stream);
				$wnd.localMediaStream = stream;
				$wnd.carregaSequenciaExpressao_j("Clica-Tira-Foto", false);
				$wnd.sendMsgText2_j(strTextoBoneco, false);

				//$wnd.alert("3");
			}, onFailSoHard);
			//$wnd.alert("4");
		} else {
			video.src = 'somevideo.webm'; // fallback.
		}


		if (!$wnd.snapshot) {
			$wnd.snapshot = function() {
				//$wnd.alert("snapshot");
				if ($wnd.localMediaStream) {
					var cw = $wnd.canvas.width;
		    		var ch = $wnd.canvas.height;
					//$wnd.alert("cw = " + cw + ", ch = " + ch);
					$wnd.ctx.drawImage($wnd.video, 0, 0, cw, ch);
					//$wnd.alert("draw ok");
					// "image/webp" works in Chrome 18. In other browsers, this will fall back to image/png.
					var strDataUrl = $wnd.canvas.toDataURL("image/png");
					//$wnd.alert("canvas.toDataUrl = " + strDataUrl);
					$doc.querySelector('.imgFoto').src = strDataUrl;
					//$wnd.alert("img ok");
					//var imgData = ctx.getImageData(0, 0, cw, ch);
					return strDataUrl;
				} else {
					return null;
				}
			}
		}


	}-*/;

	public static native void unLoadCam() /*-{
		if ($wnd.localMediaStream) {
			//$wnd.alert("unLoadCam inicio");
			$wnd.localMediaStream.stop();
			$wnd.localMediaStream = null;
			//$wnd.alert("unLoadCam fim");
		}
	}-*/;

	public static native void exportaAdicionaFotoFile(CriarComparacao2Coisas compInstance) /*-{
		$wnd.adicionaFotoFile_j = function(prodNum, dataUrl) {
			compInstance.@qualomelhor.gwt.modules.client.CriarComparacao2Coisas::addStreamFotoComparacao(ILjava/lang/String;)(prodNum, dataUrl);
		}
	}-*/;

	public static native void exportaAdicionaFotoURL(CriarComparacao2Coisas compInstance) /*-{
		$wnd.adicionaFotoURL_j = function(prodNum, url) {
			compInstance.@qualomelhor.gwt.modules.client.CriarComparacao2Coisas::addURLFotoComparacao(ILjava/lang/String;)(prodNum, url);
		}
	}-*/;

	public static native void exportaSetProduto1(CriarComparacao2Coisas compInstance) /*-{
		$wnd.setProduto1_j = function(idProd) {
			compInstance.@qualomelhor.gwt.modules.client.CriarComparacao2Coisas::setProduto1(Ljava/lang/Long;)(idProd);
		}
	}-*/;

	public static native void loadDropFileHandler(String msgNaoEhImagem) /*-{
		$wnd.handleFileSelect = function(evt) {
			//$wnd.alert("$wnd.handleFileSelect chamado");
			evt.stopPropagation();
			evt.preventDefault();

			var url = "";

		    var files;
		    if (evt.dataTransfer) {
		    	//$wnd.alert("dataTransfer");
		    	//$wnd.alert("evt.dataTransfer.types = " + evt.dataTransfer.types);
		    	
		    	if (evt.dataTransfer.types) {
		    		//$wnd.alert("evt.dataTransfer.types.len = " + evt.dataTransfer.types.length);
					//for (var i = 0; i < evt.dataTransfer.types.length; i++) {
					//	$wnd.alert("evt.dataTransfer.types[" + i + "] = " + evt.dataTransfer.types[i]);
					//}
					url = evt.dataTransfer.getData("url") || evt.dataTransfer.getData("text/uri-list");
					//$wnd.alert("url = " + url);
		    	}
		    	
		    	files = evt.dataTransfer.files; // FileList object.
		    } else {
		    	//$wnd.alert("target.files");
		    	files = evt.target.files;
		    }
	
		    // files is a FileList of File objects. List some properties.
		    var output = [];
		    // Loop through the FileList and render image files as thumbnails.
		    //$wnd.alert("files.length = " + files.length);
		    if (files.length > 0) {
			    for (var i = 0; i < files.length; i++) {
			    	//$wnd.alert("i = " + i);
					f = files[i];
					//$wnd.alert("file = " + f);
					// Only process image files.
					if (!f.type.match('image.*')) {
						//$wnd.alert("nao eh uma imagem . arquivo invalido...");
						$wnd.sendMsgText2_j(msgNaoEhImagem, true);
						continue;
					} else { 
						//$wnd.alert("eh uma imagem...");
					}
	
					//$wnd.alert("abrindo filereader...");
					var reader = new FileReader();
					//$wnd.alert("filereader ok...");
					// Closure to capture the file information.
					
	
					reader.onload = (function(theFile) {
						return function(e) {
							// Render thumbnail.
							//$wnd.alert("prodNum = " + $wnd.prodNum + ", dataUrl = [" + e.target.result + "]");
							$wnd.adicionaFotoFile_j($wnd.prodNum, e.target.result);
						};
					})(f);

	      			// Read in the image file as a data URL.
	      			//$wnd.alert("vai ler...");
	      			reader.readAsDataURL(f);
	      			//$wnd.alert("leu...");
	    		}
		    } else {
		    	//$wnd.alert("adicionando url...:" + url + " , prod:" + $wnd.prodNum);
		    	if (url != "") {
		    		$wnd.adicionaFotoURL_j($wnd.prodNum, url);
		    	}
		    }
		}

		$wnd.handleDragOver = function(evt) {
			evt.stopPropagation();
		    evt.preventDefault();
		    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
		}
	}-*/;

	public static native void startFileHandler(int prodNum) /*-{
		// Setup the dnd listeners.
		$wnd.prodNum = prodNum;
		var dropZone = $doc.getElementById("drop_zone");
		if (!$wnd.eventosAdicionados) {
			//$wnd.alert("dropZone = " + dropZone);
			dropZone.addEventListener("dragover", $wnd.handleDragOver, false);
			dropZone.addEventListener("drop", $wnd.handleFileSelect, false);
		}
		var fileSelect = $doc.getElementById("files");
		if (!$wnd.eventosAdicionados) {
			//$wnd.alert("fileSelect = " + fileSelect);
			fileSelect.addEventListener("change", $wnd.handleFileSelect, false);
		}
		$wnd.eventosAdicionados = true;
		//$wnd.alert("loadDropFileHandler fim");
	}-*/;

	@Override
	public void onModuleLoad() {
		exportaAdicionaFotoFile(this);
		exportaAdicionaFotoURL(this);
		exportaSetProduto1(this);
		exportaVerificaComparacaoCarregada(this);
		htmlFile = new HTMLPanel("<div id=\"drop_zone\" class=\"fontTextAlignCenter break-word\" style=\"width: 100%; height: 200px; display: table-cell; vertical-align: middle; background-color: white; border: thin dashed red;\">" + constants.arraste_a_imagem_neste_espaco_ou_selecione_o_arquivo_no_botao_abaixo()  + "</div>");
		System.out.println("Iniciando modulo...");
		rootSelProd1 = RootPanel.get("divSelProd1");
		rootProd1 = RootPanel.get("divProduto1");
		rootSelProd2 = RootPanel.get("divSelProd2");
		rootProd2 = RootPanel.get("divProduto2");
		rootPergunta = RootPanel.get("divPergunta");
		hasGetUserMedia();  // inicializar
		if (hasFileReader()) {
			//Window.alert("FileReader ok");
		}
		carregaLocaleAtual();
		//carregaFormComparacao2Coisas();
	}

	private void esperaGameCarregado() {
		class Contador {
			public int limite = 100;
		}
		final Contador cont = new Contador(); 
		Timer t = new Timer() {

			@Override
			public void run() {
				if (cont.limite > 0) {
					if (verificaBackGroundCarregado()) {
						this.cancel();
						carregaFormComparacao2Coisas();
					} else {
						cont.limite--;
					}
				} else {
					this.cancel();
					Window.alert("cancel.. verificaback");
					carregaFormComparacao2Coisas();
				}
			}
		};
		t.scheduleRepeating(30);
	}

	private void carregaFormComparacao2Coisas() {
		rootProd1.clear();
		rootProd2.clear();
		rootPergunta.clear();

		vertPanelPergunta = new VerticalPanel();
		rootPergunta.add(vertPanelPergunta);
		vertPanelPergunta.setStylePrimaryName("vertPanelPergunta");
		vertPanelPergunta.addStyleName("divCenter");
		vertPanelPergunta.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);

		vertPanelProd1 = new VerticalPanel();
		vertPanelProd1.setStylePrimaryName("divCenter");
		vertPanelProd1.setHeight("100%");
		vertPanelProd1.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		rootProd1.add(vertPanelProd1);

		vertPanelProd2 = new VerticalPanel();
		vertPanelProd2.setStylePrimaryName("divCenter");
		vertPanelProd2.setHeight("100%");
		rootProd2.add(vertPanelProd2);

		if (gameCarregado()) {
			//Window.alert("vai iniciar o produto e o comportamento...");
			trocaAvatarAleatorio(true);
			iniciaComportamentoAleatorio(2000, 5);
			//Window.alert("iniciou o comportamento...");
			solicitaProduto1();
			//Window.alert("solicitou o produto1...");
		} else {
			class Contador {
				public int limite = 3;
			}
			final Contador cont = new Contador();
			Timer t = new Timer() {
				@Override
				public void run() {
					if (cont.limite > 0) {
						if (gameCarregado()) {
							this.cancel();
							//iniciaComportamentoAleatorio();
							trocaAvatarAleatorio(true);
							solicitaProduto1();
						} else {
							cont.limite--;
						}
					} else {
						this.cancel();
						solicitaProduto1();
					}
				}
			};
			t.scheduleRepeating(1000);
		}
	}

	private boolean verificaComparacaoCarregada() {
		return comparacaoCarregada;
	}

	private void solicitaProduto1() {
		
		rootProd1.addStyleName("boxRoundedSelected");
		//Window.alert("solicitando produto1...1");
		//Window.alert("vai carregar a expressao");
		//Window.alert("solicitando produto1...2");

		isw1 = new ImageSliderWidget(new Image[0], ImageSliderWidget.TipoAnimacao.FADE);

		final VerticalPanel tmpVertPanelProd1_Web = new VerticalPanel();
		vertPanelProd1.add(tmpVertPanelProd1_Web);
		vertPanelAtualProd1 = tmpVertPanelProd1_Web;
		tmpVertPanelProd1_Web.setStylePrimaryName("divCenter");
		tmpVertPanelProd1_Web.setHeight("100%");

		final VerticalPanel tmpVertPanelProd1_Cam = new VerticalPanel();
		tmpVertPanelProd1_Cam.setStylePrimaryName("divCenter");
		tmpVertPanelProd1_Cam.setHeight("100%");

		final VerticalPanel tmpVertPanelProd1_File = new VerticalPanel();
		tmpVertPanelProd1_File.setStylePrimaryName("divCenter");
		tmpVertPanelProd1_File.setHeight("100%");

		HorizontalPanel horPSel = new HorizontalPanel();
		rootSelProd1.add(horPSel);
		horPSel.setSpacing(10);

		final Label lbWeb = new Label(constants.web());
		final Button btnWeb = new Button("");
		final Label lbCam = new Label(constants.camera());
		final Button btnCam = new Button("");
		final Label lbFile = new Label(constants.upload());
		final Button btnFile = new Button("");

		if (hasGetUserMedia() && hasFileReader()) {

			VerticalPanel vertPCam = new VerticalPanel();
			horPSel.add(vertPCam);

			vertPCam.add(lbCam);
			vertPCam.setCellHorizontalAlignment(lbCam, HasHorizontalAlignment.ALIGN_CENTER);
			lbCam.setStylePrimaryName("smallfont");
			lbCam.addStyleName("fontTextAlignCenter");

			vertPCam.add(btnCam);
			btnCam.setStylePrimaryName("btnCam");

			btnCam.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {

					if (vertPanelAtualProd1 != null && vertPanelAtualProd1 != tmpVertPanelProd1_Cam) {
						btnCam.addStyleName("boxShadow");
						lbCam.addStyleName("btnLinkSelecionado");
						btnWeb.removeStyleName("boxShadow");
						lbWeb.removeStyleName("btnLinkSelecionado");
						btnFile.removeStyleName("boxShadow");
						lbFile.removeStyleName("btnLinkSelecionado");
	
						ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd1, new Callable() {
							@Override
							public void call() {
								//Window.alert("call chamado");
								guiaCamProd1(tmpVertPanelProd1_Cam);
							}
						}, tmpVertPanelProd1_Cam, "", 0, 0, false, false, 0, 50, true, 2);
					}
				}
			});
		}

		VerticalPanel vertPWeb = new VerticalPanel();
		horPSel.add(vertPWeb);

		vertPWeb.add(lbWeb);
		vertPWeb.setCellHorizontalAlignment(lbWeb, HasHorizontalAlignment.ALIGN_CENTER);
		lbWeb.setStylePrimaryName("smallfont");
		lbWeb.addStyleName("fontTextAlignCenter");

		vertPWeb.add(btnWeb);
		btnWeb.setStylePrimaryName("btnWeb");

		btnWeb.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (vertPanelAtualProd1 != null && vertPanelAtualProd1 != tmpVertPanelProd1_Web) {

					btnWeb.addStyleName("boxShadow");
					lbWeb.addStyleName("btnLinkSelecionado");
					btnCam.removeStyleName("boxShadow");
					lbCam.removeStyleName("btnLinkSelecionado");
					btnFile.removeStyleName("boxShadow");
					lbFile.removeStyleName("btnLinkSelecionado");

					ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd1, new Callable () {
						@Override
						public void call() {
							//Window.alert("call chamado");
							guiaWebProd1(tmpVertPanelProd1_Web);
							//unLoadCam();
						}
						
					}, tmpVertPanelProd1_Web, "", 0, 0, false, false, 0, 50, true, 2);
				}
			}
		});

		if (hasFileReader()) {

			VerticalPanel vertPFile = new VerticalPanel();
			horPSel.add(vertPFile);

			vertPFile.add(lbFile);
			vertPFile.setCellHorizontalAlignment(lbFile, HasHorizontalAlignment.ALIGN_CENTER);
			lbFile.setStylePrimaryName("smallfont");
			lbFile.addStyleName("fontTextAlignCenter");

			vertPFile.add(btnFile);
			btnFile.setStylePrimaryName("btnFile");
			btnFile.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					if (vertPanelAtualProd1 != null && vertPanelAtualProd1 != tmpVertPanelProd1_File) {

						btnFile.addStyleName("boxShadow");
						lbFile.addStyleName("btnLinkSelecionado");
						btnCam.removeStyleName("boxShadow");
						lbCam.removeStyleName("btnLinkSelecionado");
						btnWeb.removeStyleName("boxShadow");
						lbWeb.removeStyleName("btnLinkSelecionado");

						ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd1, new Callable () {
							@Override
							public void call() {
								//Window.alert("call chamado");
								guiaFileProd1(tmpVertPanelProd1_File);
							}
							
						}, tmpVertPanelProd1_File, "", 0, 0, false, false, 0, 50, true, 2);
					}
				}
			});
		}

		/*************************************************************************/
		//Guia WEB aberto por padrao
		guiaWebProd1(tmpVertPanelProd1_Web);
		btnWeb.addStyleName("boxShadow");
		lbWeb.addStyleName("btnLinkSelecionado");
		//Fim Guia Web
		//****************************************************************************

		loadDropFileHandler(constants.este_arquivo_nao_e_uma_imagem_tente_novamente());

		comparacaoCarregada = true;
	}

	private void guiaWebProd1(final VerticalPanel tmpVertPanelProd1_Web) {
		vertPanelAtualProd1 = tmpVertPanelProd1_Web;
		guiaAtualProd1 = 1;

		carregaSequenciaExpressaoGWT("Aponta-Produto1");
		setMsgTextGWT(constants.digite_o_primeiro_item_que_voce_quer_comparar(), false);

		isw1.stopAnimacao();
		tmpVertPanelProd1_Web.clear();
		txtBuscaProd1 = new TextBox();
		txtBuscaProd1.setStylePrimaryName("textBoxPergunta");
		txtBuscaProd1.addStyleName("fontItemPergunta");
		txtBuscaProd1.addStyleName("boxShadow");
		txtBuscaProd1.addStyleName("backGroundTransition");
		txtBuscaProd1.setWidth("226px");

		HorizontalPanel horP = new HorizontalPanel();
		tmpVertPanelProd1_Web.add(horP);
		tmpVertPanelProd1_Web.setCellVerticalAlignment(horP, HasVerticalAlignment.ALIGN_MIDDLE);
		horP.add(txtBuscaProd1);

		final Button btnBuscaProd1 = new Button("&gt;&gt;");
		btnBuscaProd1.setStylePrimaryName("btnNext");
		horP.add(btnBuscaProd1);
		btnBuscaProd1.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				biProd1.addStyleName("boxShadow");
				biProd1.setBusca(txtBuscaProd1.getText());
			}
		});

		HorizontalPanel horP2 = new HorizontalPanel();
		tmpVertPanelProd1_Web.add(horP2);
		tmpVertPanelProd1_Web.setCellVerticalAlignment(horP2, HasVerticalAlignment.ALIGN_MIDDLE);
		biProd1 = new BuscaImagemWidget();
		horP2.add(biProd1);

		//vertPanelProd1.add(btnConfirmaImagens);
		//vertPanelProd1.setCellVerticalAlignment(btnConfirmaImagens, HasVerticalAlignment.ALIGN_BOTTOM);
	
		biProd1.addImagemSelecionadaHandler(new BuscaImagemEventHandler() {
			@Override
			public void onListaPronta(ImagemDisponivelEvent event) {
				//btnConfirmaImagens.setEnabled(true);
			}
	
			@Override
			public void onListaNaoPronta(ImagemNaoDisponivelEvent event) {
				//btnConfirmaImagens.setEnabled(false);
			}

			@Override
			public void onImagensJaSelecionadas(ImagensJaSelecionadasEvent event) {
				ArrayList<String> listStrImagens = biProd1.getSelectedImagesSource();

				//tmpVertPanelProd1_Web.clear();
				txtBuscaProd1.removeStyleName("boxShadow");
				for (int i = 0; i < listStrImagens.size(); i++) {
					isw1.addImage(new Image(listStrImagens.get(i)));
				}

				ClientUtils.trocaWidgetWithFunction(tmpVertPanelProd1_Web, new Callable() {
					@Override
					public void call() {
						showProd1();
					}
				}, tmpVertPanelProd1_Show, "", 0, 0, false, false, 0, 10, true, 1);
			}
		});
	}

	private void showProd1() {
		//Window.alert("mostrando prod 1");
		tmpVertPanelProd1_Show.clear();
		vertPanelAtualProd1 = tmpVertPanelProd1_Show;
		tmpVertPanelProd1_Show.setSize("100%", "100%");

		isw1.setStylePrimaryName("divCenter");
		isw1.setSize("200px", "200px");
		tmpVertPanelProd1_Show.add(isw1);
		tmpVertPanelProd1_Show.setCellHorizontalAlignment(isw1, HasHorizontalAlignment.ALIGN_CENTER);

		//Window.alert("mostrando prod 1.1");
		lbProduto1 = new Label(txtBuscaProd1.getText().trim());
		lbProduto1.setStylePrimaryName("divCenter");
		lbProduto1.addStyleName("fontTexto1");
		lbProduto1.addStyleName("fontTextAlignCenter");
		lbProduto1.setWidth("100%");
		lbProduto1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		//Window.alert("mostrando prod 1.2");
		HorizontalPanel horPTmp = new HorizontalPanel();
		tmpVertPanelProd1_Show.add(horPTmp);
		horPTmp.setWidth("100%");
		horPTmp.setStylePrimaryName("fontTextAlignCenter");
		horPTmp.addStyleName("divCenter");
		tmpVertPanelProd1_Show.setCellHorizontalAlignment(horPTmp, HasHorizontalAlignment.ALIGN_CENTER);

		//Window.alert("mostrando prod 1.3");
		if (txtBuscaProd1.getText().equals("")) {
			horPTmp.add(txtBuscaProd1);
			
		} else {
			horPTmp.add(lbProduto1);
		}

		//Window.alert("mostrando prod 1.4");
		txtBuscaProd1.setWidth("100%");
		aplicaEventoLabelProd1("", 0, 0);

		isw1.iniciaAnimacao();
		rootProd1.setHeight("350px");

		//Window.alert("mostrando prod 1.5");
		btnNextP1 = new Button(constants.proximo_item());
		tmpVertPanelProd1_Show.add(btnNextP1);
		btnNextP1.setWidth("100%");
		tmpVertPanelProd1_Show.setCellHorizontalAlignment(btnNextP1, HasHorizontalAlignment.ALIGN_CENTER);
		btnNextP1.setStylePrimaryName("btnNext");
		btnNextP1.getElement().getStyle().setFontSize(20, Unit.PX);

		btnNextP1.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				//Window.alert("disparado click event...");
				//Window.alert("txtBuscaProd1.getText() = " + txtBuscaProd1.getText());
				if (!txtBuscaProd1.getText().trim().equals("")) {
					removeEventoLabelProd1();
					rootProd1.setHeight("300px");
					btnNextP1.getElement().getStyle().setVisibility(Visibility.HIDDEN);
					solicitaProduto2();
					rootSelProd1.getElement().getStyle().setVisibility(Visibility.HIDDEN);
				} else {
					carregaSequenciaExpressaoGWT("Opps");
					setMsgTextGWT(constants.oppss_por_favor_preencha_o_nome_deste_item(), false);
					txtBuscaProd1.setFocus(true);
				}
				//Window.alert("fim do click event...");
			}
		});
		//Window.alert("mostrando prod 1.6");
	}

	private void guiaCamProd1(final VerticalPanel tmpVertPanelProd1_Cam) {
		vertPanelAtualProd1 = tmpVertPanelProd1_Cam;
		guiaAtualProd1 = 2;

		carregaSequenciaExpressaoGWT("Aponta-Camera");
		setMsgTextGWT(constants.foto_da_sua_webcam_por_favor_permissao_permissao_para_usar_sua_camera(), false);

		isw1.stopAnimacao();
		tmpVertPanelProd1_Cam.clear();
		htmlImg.setWidth("100%");
		htmlImg.getElement().getStyle().setDisplay(Display.NONE);
		//Canvas c = Canvas.createIfSupported();
		//c.getElement().setClassName("canvasVideo");
		//Context2d context = c.getContext2d();

		tmpVertPanelProd1_Cam.add(htmlP);
		tmpVertPanelProd1_Cam.add(htmlPCanvas);
		Button btnTiraFoto = new Button(constants.tirar_a_foto());
		tmpVertPanelProd1_Cam.add(btnTiraFoto);		
		btnTiraFoto.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				tmpVertPanelProd1_Cam.add(htmlImg);
				String dataUrl = foto();
				addStreamFotoComparacao(1, dataUrl);
				//Window.alert("Foto Tirada ok");
			}
		});

		loadCam(constants.clique_para_tirar_a_foto());
	}

	private void guiaFileProd1(final VerticalPanel tmpVertPanelProd1_File) {
		vertPanelAtualProd1 = tmpVertPanelProd1_File;
		guiaAtualProd1 = 3;

		carregaSequenciaExpressaoGWT("Aponta-Produto1");
		setMsgTextGWT(constants.vai_fazer_upload_selecione_ou_arreste_uma_foto_para_a_area_marcada(), false);

		isw1.stopAnimacao();
		tmpVertPanelProd1_File.clear();

		htmlImg.setWidth("100%");
		htmlImg.getElement().getStyle().setDisplay(Display.NONE);
		//Canvas c = Canvas.createIfSupported();
		//c.getElement().setClassName("canvasVideo");
		//Context2d context = c.getContext2d();

		tmpVertPanelProd1_File.add(htmlFile);
		tmpVertPanelProd1_File.add(htmlInputFile);

		startFileHandler(1);
	}

	private void addStreamFotoComparacao(int prodNum, String dataUrl) {
		//Window.alert("dataUrl = " + dataUrl);
		if (prodNum == 1) {
			listImageDataUrlProd1.add(dataUrl);
			//Window.alert("adicionou o dataurl ao lista");
			isw1.addImage(new Image(dataUrl));
			//Window.alert("adicionou a imagem do isw1");
			ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd1, new Callable() {
				@Override
				public void call() {
					showProd1();
				}
			}, tmpVertPanelProd1_Show, "", 0, 0, false, false, 0, 10, true, 1);

		} else if (prodNum == 2) {
			listImageDataUrlProd2.add(dataUrl);
			isw2.addImage(new Image(dataUrl));
			ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd2, new Callable() {
				@Override
				public void call() {
					showProd2();
				}
			}, tmpVertPanelProd2_Show, "", 0, 0, false, false, 0, 10, true, 1);

		}
	}

	private void addURLFotoComparacao(int prodNum, String url) {
		//Window.alert("dataUrl = " + dataUrl);
		if (prodNum == 1) {
			biProd1.getSelectedImagesSource().add(url);
			//Window.alert("adicionou o dataurl ao lista");
			isw1.addImage(new Image(url));
			//Window.alert("adicionou a imagem do isw1");
			ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd1, new Callable() {
				@Override
				public void call() {
					showProd1();
				}
			}, tmpVertPanelProd1_Show, "", 0, 0, false, false, 0, 10, true, 1);

		} else if (prodNum == 2) {
			if (biProd2 == null) {
				biProd2 = new BuscaImagemWidget();
			}
			biProd2.getSelectedImagesSource().add(url);
			//Window.alert("adicionou o dataurl ao lista");
			isw2.addImage(new Image(url));
			ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd2, new Callable() {
				@Override
				public void call() {
					showProd2();
				}
			}, tmpVertPanelProd2_Show, "", 0, 0, false, false, 0, 10, true, 1);

		}
	}

	private void solicitaProduto2() {
		rootProd1.removeStyleName("boxRoundedSelected");
		//txtBuscaProd1.removeStyleName("boxShadow");
		//Window.alert("solicitaProduto2 .. 1");
		isw2 = new ImageSliderWidget(new Image[0], ImageSliderWidget.TipoAnimacao.FADE);

		//Window.alert("solicitaProduto2 .. 2");
		final VerticalPanel tmpVertPanelProd2_Web = new VerticalPanel();
		vertPanelProd2.add(tmpVertPanelProd2_Web);
		vertPanelAtualProd2 = tmpVertPanelProd2_Web;
		tmpVertPanelProd2_Web.setStylePrimaryName("divCenter");
		tmpVertPanelProd2_Web.setHeight("100%");

		final VerticalPanel tmpVertPanelProd2_Cam = new VerticalPanel();
		tmpVertPanelProd2_Cam.setStylePrimaryName("divCenter");
		tmpVertPanelProd2_Cam.setHeight("100%");

		final VerticalPanel tmpVertPanelProd2_File = new VerticalPanel();
		tmpVertPanelProd2_File.setStylePrimaryName("divCenter");
		tmpVertPanelProd2_File.setHeight("100%");

		int widthRootPanelProd2 = 64;

		//Window.alert("solicitaProduto2 .. 3");
		HorizontalPanel horPSel = new HorizontalPanel();
		rootSelProd2.add(horPSel);

		final Label lbWeb = new Label(constants.web());
		final Button btnWeb = new Button("");
		final Label lbCam = new Label(constants.camera());
		final Button btnCam = new Button("");
		final Label lbFile = new Label(constants.upload());
		final Button btnFile = new Button("");

		//Window.alert("solicitaProduto2 .. 4");
		if (hasGetUserMedia()) {
			widthRootPanelProd2 += 32;
			VerticalPanel vertPCam = new VerticalPanel();
			horPSel.add(vertPCam);

			vertPCam.add(lbCam);
			vertPCam.setCellHorizontalAlignment(lbCam, HasHorizontalAlignment.ALIGN_CENTER);
			lbCam.setStylePrimaryName("smallfont");
			lbCam.addStyleName("fontTextAlignCenter");

			vertPCam.add(btnCam);
			btnCam.setStylePrimaryName("btnCam");

			btnCam.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {

					if (vertPanelAtualProd2 != null && vertPanelAtualProd2 != tmpVertPanelProd2_Cam) {

						btnCam.addStyleName("boxShadow");
						lbCam.addStyleName("btnLinkSelecionado");
						btnWeb.removeStyleName("boxShadow");
						lbWeb.removeStyleName("btnLinkSelecionado");
						btnFile.removeStyleName("boxShadow");
						lbFile.removeStyleName("btnLinkSelecionado");

						ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd2, new Callable() {
							@Override
							public void call() {
								//Window.alert("call chamado");
								guiaCamProd2(tmpVertPanelProd2_Cam);
							}
						}, tmpVertPanelProd2_Cam, "", 0, 0, false, false, 0, 50, true, 2);
					}
				}
			});
		}

		VerticalPanel vertPWeb = new VerticalPanel();
		horPSel.add(vertPWeb);

		vertPWeb.add(lbWeb);
		vertPWeb.setCellHorizontalAlignment(lbWeb, HasHorizontalAlignment.ALIGN_CENTER);
		lbWeb.setStylePrimaryName("smallfont");
		lbWeb.addStyleName("fontTextAlignCenter");

		vertPWeb.add(btnWeb);
		btnWeb.setStylePrimaryName("btnWeb");

		btnWeb.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (vertPanelAtualProd2 != null && vertPanelAtualProd2 != tmpVertPanelProd2_Web) {

					btnWeb.addStyleName("boxShadow");
					lbWeb.addStyleName("btnLinkSelecionado");
					btnCam.removeStyleName("boxShadow");
					lbCam.removeStyleName("btnLinkSelecionado");
					btnFile.removeStyleName("boxShadow");
					lbFile.removeStyleName("btnLinkSelecionado");

					ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd2, new Callable () {
						@Override
						public void call() {
							//Window.alert("call chamado");
							guiaWebProd2(tmpVertPanelProd2_Web);
							//unLoadCam();
						}

					}, tmpVertPanelProd2_Web, "", 0, 0, false, false, 0, 50, true, 2);
				}
			}
		});

		if (hasFileReader()) {

			VerticalPanel vertPFile = new VerticalPanel();
			horPSel.add(vertPFile);

			vertPFile.add(lbFile);
			vertPFile.setCellHorizontalAlignment(lbFile, HasHorizontalAlignment.ALIGN_CENTER);
			lbFile.setStylePrimaryName("smallfont");
			lbFile.addStyleName("fontTextAlignCenter");

			vertPFile.add(btnFile);
			btnFile.setStylePrimaryName("btnFile");
			btnFile.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					if (vertPanelAtualProd2 != null && vertPanelAtualProd2 != tmpVertPanelProd2_File) {

						btnFile.addStyleName("boxShadow");
						lbFile.addStyleName("btnLinkSelecionado");
						btnCam.removeStyleName("boxShadow");
						lbCam.removeStyleName("btnLinkSelecionado");
						btnWeb.removeStyleName("boxShadow");
						lbWeb.removeStyleName("btnLinkSelecionado");

						ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd2, new Callable () {
							@Override
							public void call() {
								//Window.alert("call chamado");
								guiaFileProd2(tmpVertPanelProd2_File);
							}
							
						}, tmpVertPanelProd2_File, "", 0, 0, false, false, 0, 50, true, 2);
					}
				}
			});
		}

		rootSelProd2.setWidth(widthRootPanelProd2 + "px");
		//Window.alert("solicitaProduto2 .. 4");
		/*************************************************************************/
		//Guia WEB
		if (guiaAtualProd1 == 1) {
			guiaWebProd2(tmpVertPanelProd2_Web);
			btnWeb.addStyleName("boxShadow");
			lbWeb.addStyleName("btnLinkSelecionado");

		} else if (guiaAtualProd1 == 2) {
			vertPanelProd2.add(tmpVertPanelProd2_Cam);
			vertPanelAtualProd2 = tmpVertPanelProd2_Cam;
			guiaCamProd2(tmpVertPanelProd2_Cam);
			btnCam.addStyleName("boxShadow");
			lbCam.addStyleName("btnLinkSelecionado");

		} else if (guiaAtualProd1 == 3) {
			vertPanelProd2.add(tmpVertPanelProd2_File);
			vertPanelAtualProd2 = tmpVertPanelProd2_File;
			guiaFileProd2(tmpVertPanelProd2_File);
			btnFile.addStyleName("boxShadow");
			lbFile.addStyleName("btnLinkSelecionado");
		}
		//Fim Guia Web
		//****************************************************************************

		//Window.alert("solicitaProduto2 .. fim");
	}

	private void guiaWebProd2(final VerticalPanel tmpVertPanelProd2_Web) {
		vertPanelAtualProd2 = tmpVertPanelProd2_Web;

		carregaSequenciaExpressaoGWT("Aponta-Produto2");
		setMsgTextGWT(constants.digite_o_segundo_item_que_voce_quer_comparar(), false);

		isw2.stopAnimacao();
		tmpVertPanelProd2_Web.clear();
		txtBuscaProd2 = new TextBox();
		txtBuscaProd2.setStylePrimaryName("textBoxPergunta");
		txtBuscaProd2.addStyleName("fontItemPergunta");
		txtBuscaProd2.addStyleName("boxShadow");
		txtBuscaProd2.addStyleName("backGroundTransition");
		txtBuscaProd2.setWidth("226px");

		HorizontalPanel horP = new HorizontalPanel();
		tmpVertPanelProd2_Web.add(horP);
		tmpVertPanelProd2_Web.setCellVerticalAlignment(horP, HasVerticalAlignment.ALIGN_MIDDLE);
		horP.add(txtBuscaProd2);

		final Button btnBuscaProd2 = new Button("&gt;&gt;");
		btnBuscaProd2.setStylePrimaryName("btnNext");
		horP.add(btnBuscaProd2);
		btnBuscaProd2.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				biProd2.addStyleName("boxShadow");
				biProd2.setBusca(txtBuscaProd2.getText());
			}
		});

		HorizontalPanel horP2 = new HorizontalPanel();
		tmpVertPanelProd2_Web.add(horP2);
		tmpVertPanelProd2_Web.setCellVerticalAlignment(horP2, HasVerticalAlignment.ALIGN_MIDDLE);
		biProd2 = new BuscaImagemWidget();
		horP2.add(biProd2);

		//vertPanelProd1.add(btnConfirmaImagens);
		//vertPanelProd1.setCellVerticalAlignment(btnConfirmaImagens, HasVerticalAlignment.ALIGN_BOTTOM);

		biProd2.addImagemSelecionadaHandler(new BuscaImagemEventHandler() {
			@Override
			public void onListaPronta(ImagemDisponivelEvent event) {
				//btnConfirmaImagens.setEnabled(true);
			}

			@Override
			public void onListaNaoPronta(ImagemNaoDisponivelEvent event) {
				//btnConfirmaImagens.setEnabled(false);
			}

			@Override
			public void onImagensJaSelecionadas(ImagensJaSelecionadasEvent event) {
				ArrayList<String> listStrImagens = biProd2.getSelectedImagesSource();

				tmpVertPanelProd2_Web.clear();
				txtBuscaProd2.removeStyleName("boxShadow");

				for (int i = 0; i < listStrImagens.size(); i++) {
					isw2.addImage(new Image(listStrImagens.get(i)));
				}

				ClientUtils.trocaWidgetWithFunction(tmpVertPanelProd2_Web, new Callable() {
					@Override
					public void call() {
						showProd2();
					}
				}, tmpVertPanelProd2_Show, "", 0, 0, false, false, 0, 10, true, 1);
			}
		});
	}

	private void guiaCamProd2(final VerticalPanel tmpVertPanelProd2_Cam) {
		vertPanelAtualProd2 = tmpVertPanelProd2_Cam;

		carregaSequenciaExpressaoGWT("Aponta-Camera");
		setMsgTextGWT(constants.foto_da_sua_webcam_por_favor_permissao_permissao_para_usar_sua_camera(), false);

		isw2.stopAnimacao();
		tmpVertPanelProd2_Cam.clear();
		htmlImg.setWidth("100%");
		htmlImg.getElement().getStyle().setDisplay(Display.NONE);
		//Canvas c = Canvas.createIfSupported();
		//c.getElement().setClassName("canvasVideo");
		//Context2d context = c.getContext2d();

		tmpVertPanelProd2_Cam.add(htmlP);
		tmpVertPanelProd2_Cam.add(htmlPCanvas);
		Button btnTiraFoto = new Button(constants.tirar_a_foto());
		tmpVertPanelProd2_Cam.add(btnTiraFoto);
		btnTiraFoto.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				tmpVertPanelProd2_Cam.add(htmlImg);
				String dataUrl = foto();
				addStreamFotoComparacao(2, dataUrl);
				//Window.alert("Foto Tirada ok");
			}
		});
		loadCam(constants.clique_para_tirar_a_foto());
	}

	private void guiaFileProd2(final VerticalPanel tmpVertPanelProd2_File) {
		vertPanelAtualProd2 = tmpVertPanelProd2_File;

		carregaSequenciaExpressaoGWT("Aponta-Produto2");
		setMsgTextGWT(constants.vai_fazer_upload_selecione_ou_arreste_uma_foto_para_a_area_marcada(), false);

		isw2.stopAnimacao();
		tmpVertPanelProd2_File.clear();
		htmlImg.setWidth("100%");
		htmlImg.getElement().getStyle().setDisplay(Display.NONE);
		//Canvas c = Canvas.createIfSupported();
		//c.getElement().setClassName("canvasVideo");
		//Context2d context = c.getContext2d();

		tmpVertPanelProd2_File.add(htmlFile);
		tmpVertPanelProd2_File.add(htmlInputFile);

		startFileHandler(2);
	}

	private void showProd2() {
		//Window.alert("mostrando prod 2");
		tmpVertPanelProd2_Show.clear();
		vertPanelAtualProd2 = tmpVertPanelProd2_Show;
		tmpVertPanelProd2_Show.setSize("100%", "100%");

		isw2.setStylePrimaryName("divCenter");
		isw2.setSize("200px", "200px");
		tmpVertPanelProd2_Show.add(isw2);
		tmpVertPanelProd2_Show.setCellHorizontalAlignment(isw2, HasHorizontalAlignment.ALIGN_CENTER);

		if (txtBuscaProd2 == null) {
			txtBuscaProd2 = new TextBox();
			txtBuscaProd2.setStylePrimaryName("textBoxPergunta");
			txtBuscaProd2.addStyleName("fontItemPergunta");
			txtBuscaProd2.addStyleName("boxShadow");
			txtBuscaProd2.addStyleName("backGroundTransition");
			txtBuscaProd2.setWidth("226px");
		}

		lbProduto2 = new Label(txtBuscaProd2.getText().trim());
		lbProduto2.setStylePrimaryName("divCenter");
		lbProduto2.addStyleName("fontTexto1");
		lbProduto2.addStyleName("fontTextAlignCenter");
		
		lbProduto2.setWidth("100%");
		lbProduto2.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		HorizontalPanel horPTmp = new HorizontalPanel();
		tmpVertPanelProd2_Show.add(horPTmp);
		horPTmp.setWidth("100%");
		horPTmp.setStylePrimaryName("divCenter");
		horPTmp.addStyleName("fontTextAlignCenter");
		tmpVertPanelProd2_Show.setCellHorizontalAlignment(horPTmp, HasHorizontalAlignment.ALIGN_CENTER);

		if (txtBuscaProd2.getText().equals("")) {
			horPTmp.add(txtBuscaProd2);

		} else {
			horPTmp.add(lbProduto2);
		}
		txtBuscaProd2.setWidth("100%");
		aplicaEventoLabelProd2("", 0, 0);

		isw2.iniciaAnimacao();
		rootProd2.setHeight("350px");

		Button btnNext = new Button(constants.escolher_a_pergunta() + "&nbsp;&gt;&gt;");
		tmpVertPanelProd2_Show.add(btnNext);
		btnNext.setWidth("100%");
		tmpVertPanelProd2_Show.setCellHorizontalAlignment(btnNext, HasHorizontalAlignment.ALIGN_CENTER);
		btnNext.setStylePrimaryName("btnNext");
		btnNext.getElement().getStyle().setFontSize(20, Unit.PX);

		btnNext.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (!txtBuscaProd2.getText().trim().equals("")) {
					rootProd2.setHeight("300px");
					Button b = (Button)event.getSource();
					b.getElement().getStyle().setVisibility(Visibility.HIDDEN);
					removeEventoLabelProd2();
					//Window.alert("vai carregar a escolha da pergunda...");
					rootSelProd2.getElement().getStyle().setVisibility(Visibility.HIDDEN);
					carregaFormEscolhaAPergunta();
				} else {
					Window.alert("Oppss.. Por favor, preencha o nome deste item");
					txtBuscaProd2.setFocus(true);
				}
			}
		});
	}

	private void carregaFormEscolhaAPergunta() {

		rootProd2.removeStyleName("boxRoundedSelected");
		rootPergunta.addStyleName("boxRoundedSelected");
		//rootPergunta.getElement().getStyle().setTop(370, Unit.PX);

		//ClientUtils.fadeInWidgetWithFunctionOrNot(vertPanelPergunta, null, false);				

		vertPanelPergunta.clear();

		//vertPanelPergunta.add(new Label(constants.forme_a_pergunta()));

		//tbPanelPergunta = new FlexTable();
		//tbPanelPergunta.setStylePrimaryName("tbPergunta");
		//vertPanelPergunta.setBorderWidth(1);
		//Window.alert("carregando pergunta 1..");
		String strStyle;
		int contStyle = 1;
		int numPerguntasAdicionadas = 0;
		int i = 0;
		int tamFontStyle = 22;
		//Window.alert("ParametrosSistema.SiteHost.values().length = " + ParametrosSistema.SiteHost.values().length);
		Button[] matrBtnPerg = new Button[ParametrosSistema.SiteHost.values().length];
		for (; i < ParametrosSistema.SiteHost.values().length; i++) {
			//Window.alert("locale = " + locale + ", pergunta / site = " + ParametrosSistema.SiteHost.values()[i].getPergunta() + "/" + ParametrosSistema.SiteHost.values()[i].getHost());

			if (((u != null && u.getAdmin()) || !ParametrosSistema.SiteHost.values()[i].getAdmin()) && ParametrosSistema.SiteHost.values()[i].containsLocale(locale)) {
			//if (ParametrosSistema.SiteHost.values()[i].containsLocale(locale)) {
				String perg = ParametrosSistema.SiteHost.values()[i].getPergunta();
				int siteHost = ParametrosSistema.SiteHost.values()[i].getIdSite();
				Button btnPergunta = new Button(perg + "&nbsp;<span style=\"color:green;\">" + txtBuscaProd1.getText() + "</span>&nbsp;" + constants.ou() + "&nbsp;<span style=\"color:green;\">" + txtBuscaProd2.getText() + "</span> ?");
				btnPergunta.setTitle(String.valueOf(siteHost));

				btnPergunta.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						Button b = (Button)event.getSource();
						b.setEnabled(false);
						//Window.alert("Vai gravar a pergunta..");
						System.out.println("nomeProduto1 = " + txtBuscaProd1.getText());
						System.out.println("nomeProduto2 = " + txtBuscaProd2.getText());
						System.out.println("enderecoFoto1.size = " + biProd1.getSelectedImagesSource().size());
						System.out.println("enderecoFoto2.size = " + biProd2.getSelectedImagesSource().size());
						Button btnEvent = (Button)event.getSource();
						//int idSite = Integer.parseInt(btnEvent.getTitle());
						//

						SiteHost sitePergEscolhida = SiteHost.getSiteHostPerId(Integer.parseInt(b.getTitle()));						

						//Window.alert("siteHost = " + GWT.getHostPageBaseURL());
						SiteHost site = SiteHost.getSiteHostPerHost(GWT.getHostPageBaseURL());
						//Window.alert("site = " + site.getHost());
						if (txtPerguntaPersonalizada == null) {
							txtPerguntaPersonalizada = new TextBox();
						}
						if (site.getPergunta().equals("") || (!site.equals(sitePergEscolhida))) {
							txtPerguntaPersonalizada.setText(sitePergEscolhida.getPergunta());
						}

						String strAv = getStringAvatar();
						//Window.alert("strAv = " + strAv);
						Avatar av = null;
						if (strAv == null) {
							av = ClientUtils.getRandomAvatar();
						} else {
							av = Avatar.getAvatar(strAv);
						}

						gravaComparacao2Coisas(0L, txtBuscaProd1.getText(), txtBuscaProd2.getText(), biProd1.getSelectedImagesSource(), listImageDataUrlProd1, biProd2.getSelectedImagesSource(), listImageDataUrlProd2, site, txtPerguntaPersonalizada.getText(), av);
					}
				});

				strStyle = "btnPergunta" + contStyle;
				btnPergunta.setStylePrimaryName(strStyle);
				btnPergunta.setWidth("100%");

				String per = perg + " " + txtBuscaProd1.getText() + " " + constants.ou() + " " + txtBuscaProd2.getText() + " ?";
				if (per.length() > 38) {
					tamFontStyle = 18;
				}
				if (per.length() > 48) {
					tamFontStyle = 15;
				}

				vertPanelPergunta.add(btnPergunta);
				numPerguntasAdicionadas++;
				contStyle++;
				matrBtnPerg[i] = btnPergunta;
			}
		}

		for (int j = 0; j < matrBtnPerg.length; j++) {
			if (matrBtnPerg[j] != null) {
				matrBtnPerg[j].getElement().getStyle().setFontSize(tamFontStyle, Unit.PX);
			}
		}

		//Window.alert("carregando pergunta 2..");
		if (numPerguntasAdicionadas > 0) {
			strStyle = "btnPergunta" + contStyle;
			Button btnPergConf = new Button(constants.quero_mudar_a_pergunta());
			btnPergConf.setStylePrimaryName(strStyle);
			btnPergConf.setWidth("100%");
			btnPergConf.getElement().getStyle().setFontSize(tamFontStyle, Unit.PX);

			//Window.alert("carregando pergunta 2.1..");
			vertPanelPergunta.add(btnPergConf);
			vertPanelPergunta.setCellHorizontalAlignment(btnPergConf, HasHorizontalAlignment.ALIGN_CENTER);
			btnPergConf.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					Button b = (Button)event.getSource();
					b.setEnabled(false);
					ClientUtils.trocaWidgetWithFunction(vertPanelPergunta,  new Callable() {
						@Override
						public void call() {
							carregaFormQualAPergunta(true);						
						}
					}, vertPanelPergunta, "", 0, 0, false, false, 0, 50, true, 1);
				}
			});

			carregaSequenciaExpressaoGWT("Aponta-Abaixo");
			setMsgTextGWT(constants.escolha_a_melhor_pergunta_para_comparar_estes_itens(), false);

		} else {
			//ClientUtils.trocaWidgetWithFunction(vertPanelPergunta,  new Callable() {
			//	@Override
			//	public void call() {
					carregaFormQualAPergunta(false);						
			//	}
			//}, vertPanelPergunta, "", 0, 0, false, false, 0, 50, false);
		}
		rootPergunta.getElement().getStyle().setDisplay(Display.BLOCK);
		//Window.alert("carregando pergunta 3..");
	}

	private void carregaFormQualAPergunta(boolean botaoVoltar) {

		vertPanelPergunta.clear();

		carregaSequenciaExpressaoGWT("Aponta-Abaixo");
		setMsgTextGWT(constants.voce_pode_alterar_a_pergunta_da_forma_que_achar_mais_conveniente(), false);

		txtBuscaProd1.addStyleName("boxShadow");
		//txtBuscaProd1.setTitle("XXXXXXXXXXXX");
		txtBuscaProd1.getElement().setId("txtBuscaProd1");

		txtBuscaProd2.addStyleName("boxShadow");
		//txtBuscaProd2.setTitle(constants.clique_para_alterar_o_nome_deste_item());
		txtBuscaProd2.getElement().setId("txtBuscaProd2");

		VerticalPanel vertPanel = new VerticalPanel();
		vertPanelPergunta.add(vertPanel);
		vertPanel.setStylePrimaryName("boxRounded2");

		tbPanelPergunta = new FlexTable();
		vertPanel.add(tbPanelPergunta);
		tbPanelPergunta.setStylePrimaryName("divCenter");
		tbPanelPergunta.setHeight("80px");
		//tbPanelPergunta.setBorderWidth(1);

		String perg = "-";
		for (int i = 0; i < ParametrosSistema.SiteHost.values().length; i++) {
			if (((u != null && u.getAdmin()) || !ParametrosSistema.SiteHost.values()[i].getAdmin()) && ParametrosSistema.SiteHost.values()[i].containsLocale(locale)) {
				perg = ParametrosSistema.SiteHost.values()[i].getPergunta();
				break;
			}
		}

		lbPergPersonalizada = new Label();
		tbPanelPergunta.setWidget(0, 0, lbPergPersonalizada);

		lbPergPersonalizada.setStylePrimaryName("labelItem");
		lbPergPersonalizada.addStyleName("fontItemPergunta");
		lbPergPersonalizada.setWidth("100px");
		lbPergPersonalizada.setText(perg);
		lbPergPersonalizada.getElement().setId("lbPergPersonalizada");
		lbPergPersonalizada.setTitle(constants.escolha_a_melhor_pergunta_para_comparar_estes_itens());

		txtPerguntaPersonalizada = new TextBox();
		txtPerguntaPersonalizada.getElement().setId("txtPerguntaPersonalizada");
		//txtPerguntaPersonalizada.setTitle();
		txtPerguntaPersonalizada.setStylePrimaryName("textBoxPerguntaEdicao");
		txtPerguntaPersonalizada.addStyleName("fontPergunta");
		txtPerguntaPersonalizada.addStyleName("boxShadow");
		txtPerguntaPersonalizada.addStyleName("fontTextAlignCenter");

		aplicaEventoLabelPergPersonalizada();

		lbProduto1 = new Label();
		tbPanelPergunta.setWidget(0, 1, lbProduto1);

		txtBuscaProd1.setWidth("100px");
		aplicaEventoLabelProd1("flextable", 0, 1);

		lbProduto1.setStylePrimaryName("labelItem");
		lbProduto1.addStyleName("fontItemPergunta");
		lbProduto1.setWidth("100px");
		lbProduto1.setText(txtBuscaProd1.getText());
		lbProduto1.getElement().setId("lbProduto1");
		lbProduto1.setTitle(constants.clique_para_alterar_o_nome_deste_item());

		HTMLPanel lbOu = new HTMLPanel("&nbsp;" + constants.ou() + "&nbsp;");
		lbOu.setStylePrimaryName("fontPergunta");
		tbPanelPergunta.setWidget(0, 2, lbOu);

		lbProduto2 = new Label();
		tbPanelPergunta.setWidget(0, 3, lbProduto2);

		txtBuscaProd2.setWidth("100px");
		aplicaEventoLabelProd2("flextable", 0, 3);

		lbProduto2.setStylePrimaryName("labelItem");
		lbProduto2.addStyleName("fontItemPergunta");
		lbProduto2.setWidth("100px");
		lbProduto2.setText(txtBuscaProd2.getText());
		lbProduto2.getElement().setId("lbProduto2");
		lbProduto2.setTitle(constants.clique_para_alterar_o_nome_deste_item());		

//		lbPerguntaFinal = new Label(listPerguntas.getItemText(listPerguntas.getSelectedIndex()) + " " + txtPerguntaIntermed.getText().trim() + " " + txtBuscaProd1.getText().trim() + constants.ou() + " " + txtBuscaProd2.getText());
//		vertPanelPergunta.add(lbPerguntaFinal);

		vertPanelPergunta.add(new HTMLPanel("<br>"));

		VerticalPanel vertPanelBtn = new VerticalPanel();
		vertPanelPergunta.add(vertPanelBtn);
		vertPanelBtn.setStylePrimaryName("divCenter");
		vertPanelPergunta.setCellHorizontalAlignment(vertPanelBtn, HasHorizontalAlignment.ALIGN_CENTER);
		vertPanelBtn.setWidth("400px");

		Button btnGravar = new Button(constants.finalizar_a_pergunta());
		vertPanelBtn.add(btnGravar);
		btnGravar.setStylePrimaryName("btnPergunta1");
		btnGravar.setWidth("100%");

		btnGravar.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Button b = (Button)event.getSource();
				b.setEnabled(false);
				//Window.alert("txtPerguntaPersonalizada.getText() = " + txtPerguntaPersonalizada.getText());
				//System.out.println("nomeProduto1 = " + txtBuscaProd1.getText());
				//System.out.println("nomeProduto2 = " + txtBuscaProd2.getText());
				//System.out.println("enderecoFoto1.size = " + biProd1.getSelectedImagesSource().size());
				//System.out.println("enderecoFoto2.size = " + biProd2.getSelectedImagesSource().size());
				String host = GWT.getHostPageBaseURL().replace("http://", "");
				if (host.substring(host.length() - 1).equals("/")) {
					host = host.substring(0, host.length() - 1);
				}
				Window.alert("GWT.getHostPageBaseURL() = [" + host + "]");
				//host = "www.qual-o-melhor.com";
				SiteHost site = SiteHost.getSiteHostPerHost(host);
				Window.alert("site = " + site.getHost());
				if (!site.getPergunta().equals("") && txtPerguntaPersonalizada.getText().toLowerCase().indexOf(site.getPergunta().toLowerCase()) == 0) {
					txtPerguntaPersonalizada.setText(txtPerguntaPersonalizada.getText().substring(site.getPergunta().length()).trim());
				}

				String strAv = getStringAvatar();
				//Window.alert("strAv = " + strAv);
				Avatar av = null;
				if (strAv == null) {
					av = ClientUtils.getRandomAvatar();
				} else {
					av = Avatar.getAvatar(strAv);
				}
				//Window.alert("vai gravar 2");

				if (biProd2 == null) {
					biProd2 = new BuscaImagemWidget();
				}

				gravaComparacao2Coisas(0L, txtBuscaProd1.getText(), txtBuscaProd2.getText(), biProd1.getSelectedImagesSource(), listImageDataUrlProd1, biProd2.getSelectedImagesSource(), listImageDataUrlProd2, site, txtPerguntaPersonalizada.getText(), av);
			}
		});

		Button btnVoltar = new Button(constants.voltar());
		if (botaoVoltar) {
			vertPanelBtn.add(btnVoltar);
		}
		btnVoltar.setStylePrimaryName("btnPergunta4");
		btnVoltar.setWidth("100%");

		btnVoltar.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Button b = (Button)event.getSource();
				b.setEnabled(false);
				ClientUtils.trocaWidgetWithFunction(vertPanelPergunta,  new Callable() {
					@Override
					public void call() {
						carregaFormEscolhaAPergunta();
					}
				}, vertPanelPergunta, "", 0, 0, false, false, 0, 50, true, 1);
			}
		});

		Label lbQ = new Label("?");
		lbQ.setStylePrimaryName("fontPergunta");
		tbPanelPergunta.setWidget(0, 4, lbQ);
		//Window.alert("vai aplicar tooltip gwt...");
		aplyToolTip();
	}

	private void aplicaEventoLabelPergPersonalizada() {
		txtPerguntaPersonalizada.setWidth("300px");
		txtPerguntaPersonalizada.setText(lbPergPersonalizada.getText());
		lbPergPersonalizada.setWidth("300px");
		lbHldRegisPerg = lbPergPersonalizada.addMouseOverHandler(new MouseOverHandler() {
			@Override
			public void onMouseOver(MouseOverEvent event) {
				if (lbHldRegisPerg != null) {
					lbHldRegisPerg.removeHandler();
					lbHldRegisPerg = null;
				}
				txtPerguntaPersonalizada.setStylePrimaryName("textBoxPerguntaEdicao");
				ClientUtils.trocaWidgetWithFunction(lbPergPersonalizada,
													new Callable() {
														@Override
														public void call() {
															//registrar o evento depois de 5segs pra dar tempo do usuario não se perder
															txtPerguntaPersonalizada.selectAll();
															lbHldRegisPerg = txtPerguntaPersonalizada.addMouseOutHandler(new MouseOutHandler() {
																@Override
																public void onMouseOut(MouseOutEvent event) {
																	if (lbHldRegisPerg != null) {
																		lbHldRegisPerg.removeHandler();
																		lbHldRegisPerg = null;
																	}
																	if (lbHldRegisPerg_blur != null) {
																		lbHldRegisPerg_blur.removeHandler();
																		lbHldRegisPerg_blur = null;
																	}
																	lbPergPersonalizada.setText(txtPerguntaPersonalizada.getText());
																	ClientUtils.trocaWidgetWithFunction(txtPerguntaPersonalizada,
																									new Callable() {
																										@Override
																										public void call() {
																											aplicaEventoLabelPergPersonalizada();	
																										}
																									}, lbPergPersonalizada, "flextable", 0, 0, false, false, 0, 10, true, 2);
																}
															});

															lbHldRegisPerg_blur = txtPerguntaPersonalizada.addBlurHandler(new BlurHandler() {
																@Override
																public void onBlur(BlurEvent event) {
																	if (lbHldRegisPerg_blur != null) {
																		lbHldRegisPerg_blur.removeHandler();
																		lbHldRegisPerg_blur = null;
																	}
																	if (lbHldRegisPerg != null) {
																		lbHldRegisPerg.removeHandler();
																		lbHldRegisPerg = null;
																	}
																	lbPergPersonalizada.setText(txtPerguntaPersonalizada.getText());

																	ClientUtils.trocaWidgetWithFunction(txtPerguntaPersonalizada,
																									new Callable() {
																										@Override
																										public void call() {
																											aplicaEventoLabelPergPersonalizada();
																										}
																														
																									}, lbPergPersonalizada, "flextable", 0, 0, false, false, 0, 10, true, 2);
																}
															});

														}
													},
													txtPerguntaPersonalizada, "flextable", 0, 0, true, false, 300, 10, true, 2);
			}
		});
	}

	private void removeEventoLabelProd1() {
		if (lbHldRegisProd1 != null) {
			lbHldRegisProd1.removeHandler();
			lbHldRegisProd1 = null;
		}
		if (lbHldRegisProd1_blur != null) {
			lbHldRegisProd1_blur.removeHandler();
			lbHldRegisProd1_blur = null;
		}
		//Window.alert("txtBuscaProd1 = [" + txtBuscaProd1.getText() + "], lbProd1 = [" + lbProduto1.getText() + "]");
		if (!txtBuscaProd1.getText().equals(lbProduto1.getText())) {
			lbProduto1.setText(txtBuscaProd1.getText().trim());
			ClientUtils.trocaWidgetWithFunction(txtBuscaProd1,
					new Callable() {
						@Override
						public void call() {
						}
					},
					lbProduto1, "", 0, 0, false, false, 0, 10, true, 1);
		}
	}

	private void aplicaEventoLabelProd1(final String parentType, final int param1, final int param2) {
		if (lbHldRegisProd1 != null) {
			lbHldRegisProd1.removeHandler();
			lbHldRegisProd1 = null;
		}
		lbHldRegisProd1 = lbProduto1.addMouseOverHandler(new MouseOverHandler() {
			@Override
			public void onMouseOver(MouseOverEvent event) {
				if (lbHldRegisProd1 != null) {
					lbHldRegisProd1.removeHandler();
					lbHldRegisProd1 = null;
				}
				txtBuscaProd1.setStylePrimaryName("textBoxPerguntaEdicao");
				ClientUtils.trocaWidgetWithFunction(lbProduto1,
													new Callable() {
														@Override
														public void call() {
															txtBuscaProd1.selectAll();
															lbHldRegisProd1 = txtBuscaProd1.addMouseOutHandler(new MouseOutHandler() {
																@Override
																public void onMouseOut(MouseOutEvent event) {
																	//Window.alert("mouseout");
																	if (lbHldRegisProd1 != null) {
																		lbHldRegisProd1.removeHandler();
																		lbHldRegisProd1 = null;
																	}
																	if (lbHldRegisProd1_blur != null) {
																		lbHldRegisProd1_blur.removeHandler();
																		lbHldRegisProd1_blur = null;
																	}
																	lbProduto1.setText(txtBuscaProd1.getText());
																	ClientUtils.trocaWidgetWithFunction(txtBuscaProd1,
																										new Callable() {
																											@Override
																											public void call() {
																												aplicaEventoLabelProd1(parentType, param1, param2);
																											}
																										},
																										lbProduto1, parentType, param1, param2, false, false, 0, 10, true, 2);
																}
															});

															lbHldRegisProd1_blur = txtBuscaProd1.addBlurHandler(new BlurHandler() {
																@Override
																public void onBlur(BlurEvent event) {
																	//Window.alert("blurout");
																	if (lbHldRegisProd1_blur != null) {
																		lbHldRegisProd1_blur.removeHandler();
																		lbHldRegisProd1_blur = null;
																	}
																	if (lbHldRegisProd1 != null) {
																		lbHldRegisProd1.removeHandler();
																		lbHldRegisProd1 = null;
																	}
																	lbProduto1.setText(txtBuscaProd1.getText());

																	ClientUtils.trocaWidgetWithFunction(txtBuscaProd1,
																										new Callable() {
																											@Override
																											public void call() {
																												aplicaEventoLabelProd1(parentType, param1, param2);
																											}
																										},
																										lbProduto1, parentType, param1, param2, false, false, 0, 10, true, 2);
																}
															});

														}
													},
													txtBuscaProd1, parentType, param1, param2, true, false, 100, 10, true, 2);
			}
		});
	}

	private void removeEventoLabelProd2() {
		if (lbHldRegisProd2 != null) {
			lbHldRegisProd2.removeHandler();
			lbHldRegisProd2 = null;
		}
		if (lbHldRegisProd2_blur != null) {
			lbHldRegisProd2_blur.removeHandler();
			lbHldRegisProd2_blur = null;
		}
		//Window.alert("txtBuscaProd1 = [" + txtBuscaProd1.getText() + "], lbProd1 = [" + lbProduto1.getText() + "]");
		if (!txtBuscaProd2.getText().equals(lbProduto2.getText())) {
			lbProduto2.setText(txtBuscaProd2.getText().trim());
			ClientUtils.trocaWidgetWithFunction(txtBuscaProd2,
					new Callable() {
						@Override
						public void call() {
						}
					},
					lbProduto2, "", 0, 0, false, false, 0, 10, true, 1);
		}
	}

	private void aplicaEventoLabelProd2(final String parentType, final int param1, final int param2) {
		lbHldRegisProd2 = lbProduto2.addMouseOverHandler(new MouseOverHandler() {
			@Override
			public void onMouseOver(MouseOverEvent event) {
				if (lbHldRegisProd2 != null) {
					lbHldRegisProd2.removeHandler();
					lbHldRegisProd2 = null;
				}
				txtBuscaProd2.setStylePrimaryName("textBoxPerguntaEdicao");
				ClientUtils.trocaWidgetWithFunction(lbProduto2,
													new Callable() {
														@Override
														public void call() {
															txtBuscaProd2.selectAll();
															lbHldRegisProd2 = txtBuscaProd2.addMouseOutHandler(new MouseOutHandler() {
																@Override
																public void onMouseOut(MouseOutEvent event) {
																	if (lbHldRegisProd2 != null) {
																		lbHldRegisProd2.removeHandler();
																		lbHldRegisProd2 = null;
																	}
																	if (lbHldRegisProd2_blur != null) {
																		lbHldRegisProd2_blur.removeHandler();
																		lbHldRegisProd2_blur = null;
																	}
																	lbProduto2.setText(txtBuscaProd2.getText());
																	ClientUtils.trocaWidgetWithFunction(txtBuscaProd2,
																										new Callable() {
																											@Override
																											public void call() {
																												aplicaEventoLabelProd2(parentType, param1, param2);
																											}
																										},
																										lbProduto2, parentType, param1, param2, false, false, 0, 10, true, 2);
																}
															});

															lbHldRegisProd2_blur = txtBuscaProd2.addBlurHandler(new BlurHandler() {
																@Override
																public void onBlur(BlurEvent event) {
																	if (lbHldRegisProd2_blur != null) {
																		lbHldRegisProd2_blur.removeHandler();
																		lbHldRegisProd2_blur = null;
																	}
																	if (lbHldRegisProd2 != null) {
																		lbHldRegisProd2.removeHandler();
																		lbHldRegisProd2 = null;
																	}
																	lbProduto2.setText(txtBuscaProd2.getText());

																	ClientUtils.trocaWidgetWithFunction(txtBuscaProd2,
																										new Callable() {
																											@Override
																											public void call() {
																												aplicaEventoLabelProd2(parentType, param1, param2);
																											}
																										},
																										lbProduto2, parentType, param1, param2, false, false, 0, 10, true, 2);
																}
															});

														}
													},
													txtBuscaProd2, parentType, param1, param2, true, false, 100, 10, true, 2);
							
			}
		});
	}

	private void gravaComparacao2Coisas(Long idUsuario, String nomeProduto1, String nomeProduto2, ArrayList<String> listEnderecoFotoProd1, ArrayList<String> listImagesDataUrlProd1, ArrayList<String> listEnderecoFotoProd2, ArrayList<String> listImagesDataUrlProd2, SiteHost site, String complementoPergunta, Avatar av) {
		if (serviceSupportSvc == null) {
			serviceSupportSvc = GWT.create(ISessionSuportService.class);
		}

		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
			@Override
			public void onUncaughtException(Throwable e) {
				e.printStackTrace();
				System.out.println("Excecao nao tratada em Horario Carrega Sessao !!!!!!!!!!");
			}
		});

		AsyncCallback<Comparacao> callback = new AsyncCallback<Comparacao>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Erro ao tentar gravar! Por favor, aperte a tecla F5 do seu teclado para atualizar!");
			}

			@Override
			public void onSuccess(Comparacao comp) {
				if (comp == null) {
					Window.alert("Erro ao tentar gravar! Por favor, aperte a tecla F5 do seu teclado para atualizar! - null");
					hideDivBloqueio();
				} else {

					// Redireciona para a pagina da comparacao..
					// Verifica se o usuario esta conectado e sugere um metodo de compartilhamento
					//Window.alert("Comparacao gravada. redirecionando...");
					Window.Location.replace("/comparacao/" + comp.getPath(ParametrosSistema.SiteHost.SITE_QUAL_O_MELHOR) + "?new=true");
				}
			}
		};
		System.out.println("Salvando comparacao: idUsuario: " + idUsuario + ", nomeProduto1 = " + nomeProduto1 + ", nomeProduto2 = " + nomeProduto2 + ", enderecoFoto1.size = " + listEnderecoFotoProd1.size() + ", enderecoFoto2.size = " + listEnderecoFotoProd2.size());
		//Window.alert("listDataUrlProd1.size = " + listImagesDataUrlProd1.size());
		//Window.alert("listDataUrlProd1.size = " + listImagesDataUrlProd2.size());
		//Window.alert("Salvando comparacao: idUsuario: " + idUsuario + ", nomeProduto1 = " + nomeProduto1 + ", nomeProduto2 = " + nomeProduto2 + ", enderecoFoto1.size = " + listEnderecoFotoProd1.size() + ", enderecoFoto2.size = " + listEnderecoFotoProd2.size());
		showDivBloqueio();
		serviceSupportSvc.gravaComparacao2Coisas(idUsuario, nomeProduto1, nomeProduto2, listEnderecoFotoProd1, listImagesDataUrlProd1, listEnderecoFotoProd2, listImagesDataUrlProd2, site, locale, complementoPergunta, av, callback);
	}

	private void carregaUsuarioAtual() {
		if (serviceSupportSvc == null) {
			serviceSupportSvc = GWT.create(ISessionSuportService.class);
		}

		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
			@Override
			public void onUncaughtException(Throwable e) {
				e.printStackTrace();
				System.out.println("Excecao nao tratada em Horario Carrega Sessao !!!!!!!!!!");
			}
		});

		AsyncCallback<Usuario> callback = new AsyncCallback<Usuario>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Erro ao tentar carregar a sessao! Por favor, aperte a tecla F5 do seu teclado para atualizar!");
			}

			@Override
			public void onSuccess(Usuario user) {
				//Window.alert("Sessao sucess!");
				if (user != null) {
					u = user;
					/*
					if (u != null) {
						Window.alert("u.getNome = " + u.getNomeUsuario());
					} else {
						Window.alert("u = null");
					}
					*/
				} else {
					u = null;
				}
				esperaGameCarregado();
				//carregaFormComparacao2Coisas();
			}
		};
		//Window.alert("carregando sessao...");
		serviceSupportSvc.carregaUsuarioAtual(callback);
	}

	private void setProduto1(final Long idProd) {
		if (serviceSupportSvc == null) {
			serviceSupportSvc = GWT.create(ISessionSuportService.class);
		}

		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
			@Override
			public void onUncaughtException(Throwable e) {
				e.printStackTrace();
				System.out.println("Excecao nao tratada em Horario Carrega Sessao !!!!!!!!!!");
			}
		});

		final AsyncCallback<Produto> callback = new AsyncCallback<Produto>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Erro ao tentar carregar a sessao! Por favor, aperte a tecla F5 do seu teclado para atualizar!");
			}

			@Override
			public void onSuccess(final Produto prod) {
				//Window.alert("produto success!");
				if (prod != null) {
					txtBuscaProd1.setText(prod.getNomeProduto());
					//Window.alert("setou o nome do produto.. ok: " + prod.getListEnderecoFoto().size());
					for (int i = 0; i < prod.getListEnderecoFoto().size(); i++) {
						isw1.addImage(new Image(prod.getListEnderecoFoto().get(i)));
					}
					ClientUtils.trocaWidgetWithFunction(vertPanelAtualProd1, new Callable() {
						@Override
						public void call() {
							showProd1();
							biProd1.setSelectedImagesSource(prod.getListEnderecoFoto());
							//Window.alert("showProd1 ok..");
							Timer t = new Timer() {								
								@Override
								public void run() {
									btnNextP1.fireEvent(new GwtEvent<ClickHandler>() {
										@Override
										public com.google.gwt.event.shared.GwtEvent.Type<ClickHandler> getAssociatedType() {
											return ClickEvent.getType();
										}
										@Override
										protected void dispatch(ClickHandler handler) {
											handler.onClick(null);
										}
									});
								}
							};
							t.schedule(1000);
						}
					}, tmpVertPanelProd1_Show, "", 0, 0, false, false, 0, 10, true, 1);


				} else {
					Window.alert("Nao foi possivel carregar o produto! Por favor, aperte a tecla F5 do seu teclado para atualizar!");
				}
			}
		};

		serviceSupportSvc.carregaProduto(Long.parseLong(String.valueOf(idProd)), callback);
	}

	private void carregaLocaleAtual() {
		if (serviceSupportSvc == null) {
			serviceSupportSvc = GWT.create(ISessionSuportService.class);
		}

		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
			@Override
			public void onUncaughtException(Throwable e) {
				e.printStackTrace();
				System.out.println("Excecao nao tratada em Horario Carrega Sessao !!!!!!!!!!");
			}
		});

		AsyncCallback<String> callback = new AsyncCallback<String>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Erro ao tentar carregar a sessao! Por favor, aperte a tecla F5 do seu teclado para atualizar!");
			}

			@Override
			public void onSuccess(String loc) {
				//Window.alert("Locale sucess!");
				if (loc != null) {
					locale = loc;
				} else {
					locale = LocaleInfo.getCurrentLocale().getLocaleName();
				}
				//Window.alert("locale = " + locale);
				carregaUsuarioAtual();
			}
		};
		//Window.alert("carregando locale...");
		serviceSupportSvc.carregaLocaleAtual(callback);
	}
}